<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="代理名称">
                <a-input v-model="queryParam.name" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号">
                <a-input v-model="queryParam.phone" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="关联合伙人">
                <partner-selection v-model="queryParam.affiliated_partner"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="合伙人手机号">
                <a-input v-model="queryParam.affiliated_partner_phone" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="直接邀请人手机号">
                <a-input v-model="queryParam.direct_inviter_phone" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="间接邀请人手机号">
                <a-input v-model="queryParam.indirect_inviter_phone" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="代理商等级">
                <a-select v-model="queryParam.level" placeholder="请选择" default-value="">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="1">群主</a-select-option>
                  <a-select-option value="2">精英</a-select-option>
                  <a-select-option value="3">大咖</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="代理标签">
                <agent-label-selection v-model="queryParam.labels" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="加入时间">
                <a-range-picker :allowClear="true" ref="createdAtRangePicker" @change="createdAtRangePickerOnChange"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="销售时段">
                <a-range-picker
                  :allowClear="true"
                  ref="performanceRangePicker"
                  @change="performanceRangePickerOnChange"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
                <a-button style="margin-left: 8px" @click="handleExport">导出</a-button>
                <a-button style="margin-left: 8px" @click="handleExport(true)">大数据导出</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="() => { this.$router.push({ name: 'agent_create' }) }">新建
        </a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1300 }"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="tags" slot-scope="text, record">
          <a-tag v-for="(tag, index) in record.labels" :key="index">{{ tag.name }}</a-tag>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="$router.push({ name: 'agent_info', params: { id: record.id } })">详情</a>

            <a-divider type="vertical"/>

            <a @click="handleEdit(record)">编辑</a>

            <a-divider type="vertical"/>

            <a-popconfirm placement="top" @confirm="handleStatus(record)">
              <template slot="title">
                确定要{{ statusActionMap[record.status]['text'] }}吗?
              </template>
              <a>{{ statusActionMap[record.status]['text'] }}</a>
            </a-popconfirm>

          </template>
        </span>

        <span slot="title">
        <a-row type="flex" justify="start" :gutter="16">
          <a-col>
            <a-button @click="exportBalanceTemplate" type="link">批量操作可提现金额模板</a-button>
          </a-col>
          <a-col>
            <progress-time-line
              title="批量操作可提现余额"
              btn-title="批量操作可提现余额"
              :steps="[{ title: '读取文件'}, { title: '上传处理'}, { title: '完成' }]"
              :handle-raw="handleBalance"
            />
          </a-col>

          <a-col>
            <a-button @click="exportUnextractableBalanceTemplate" type="link">批量操作不可提现金额模板</a-button>
          </a-col>
          <a-col>
            <progress-time-line
              title="批量操作不可提现余额"
              btn-title="批量操作不可提现余额"
              :steps="[{ title: '读取文件'}, { title: '上传处理'}, { title: '完成' }]"
              :handle-raw="handleUnextractableBalance"
            />
          </a-col>
        </a-row>
      </span>
      </s-table>
    </a-card>
  </div>
</template>

<script>
  import { STable } from '@/components'
  import { adjustAgentBalance, getAgentList, updateAgentStatus } from '@/api/agent'
  import { formatAmount } from '@/utils/util'
  import PartnerSelection from '@/components/PartnerSelection/PartnerSelection'
  import XLSX from 'xlsx'
  import ProgressTimeLine from '@/components/ProgressTimeLine/ProgressTimeLine'
  import AgentLabelSelection from '@/components/AgentLabelSelection/AgentLabelSelection'

  const LEVEL_MAP = {
    1: '群主',
    2: '精英',
    3: '大咖'
  }

  const STATUS_ACTION_MAP = {
    1: {
      text: '禁用',
      action: 2
    },
    2: {
      text: '启用',
      action: 1
    }
  }

  const STATUS_MAP = {
    1: '启用',
    2: '禁用'
  }

  export default {
    name: 'List',
    components: {
      AgentLabelSelection,
      ProgressTimeLine,
      PartnerSelection,
      STable
    },
    data () {
      return {
        formRaw: {},
        mdl: {},
        statusActionMap: STATUS_ACTION_MAP,
        // 查询参数
        queryParam: {},
        // 表头
        columns: [
          {
            title: '代理名称',
            dataIndex: 'name'
          },
          {
            title: '等级',
            customRender: record => LEVEL_MAP[record.level]
          },
          {
            title: '手机号',
            dataIndex: 'phone'
          },
          {
            title: '账户余额',
            customRender: record => {
              return formatAmount(record.balance)
            }
          },
          {
            title: '不可提余额',
            customRender: record => formatAmount(record.unextractable_balance)
          },
          {
            title: '个人业绩',
            customRender: record => formatAmount(record.personal_performance)
          },
          {
            title: '团队业绩',
            customRender: record => formatAmount(record.team_performance)
          },
          {
            title: '上级邀请人',
            dataIndex: 'direct_inviter.name'
          },
          {
            title: '直接邀请数',
            dataIndex: 'number_of_direct_inviter'
          },
          {
            title: '间接邀请数',
            dataIndex: 'number_of_indirect_inviter'
          },
          {
            title: '关联合伙人',
            dataIndex: 'affiliated_partner.name'
          },
          {
            title: '团队大咖',
            dataIndex: 'team_leader'
          },
          {
            title: '标签',
            scopedSlots: { customRender: 'tags' }
          },
          {
            title: '状态',
            dataIndex: 'status',
            customRender: status => STATUS_MAP[status]
          },
          {
            title: '加入时间',
            dataIndex: 'created_at'
          },
          {
            title: '登入次数',
            dataIndex: 'login_frequency'
          },
          {
            title: '最后登入时间',
            dataIndex: 'last_time_of_login'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: '150px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return getAgentList(Object.assign(parameter, this.queryParam))
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    methods: {
      handleEdit (record) {
        this.$router.push({ name: 'agent_edit', query: { id: record.id } })
      },
      formVisibleEvent (val) {
        this.formVisible = val
        this.formRaw = {}
      },
      refreshList () {
        this.$refs.table.refresh()
      },
      createdAtRangePickerOnChange (date, dateString) {
        this.queryParam.created_at_begin = dateString[0]
        this.queryParam.created_at_end = dateString[1]
      },
      performanceRangePickerOnChange (date, dateString) {
        this.queryParam.performance_range_begin = dateString[0]
        this.queryParam.performance_range_end = dateString[1]
      },
      handleReset () {
        this.queryParam = {}
        this.$refs.createdAtRangePicker.$refs.picker.clearSelection(new MouseEvent('click'))
        this.$refs.performanceRangePicker.$refs.picker.clearSelection(new MouseEvent('click'))
      },
      handleStatus (record) {
        updateAgentStatus(record.id, STATUS_ACTION_MAP[record.status]['action']).then(res => this.$refs.table.refresh())
      },
      handleExport (isAsync = false) {
        const exportParam = { export: true }
        ;(isAsync === true) && Object.assign(exportParam, { async: true })

        getAgentList(Object.assign(exportParam, this.queryParam)).then(_ => {
          (isAsync === true) && this.$notification.success({ message: '添加任务成功,请关注[系统-异步导出任务]' })
        })
      },
      /**
       * 导出批量操作不可提现余额模板
       */
      exportBalanceTemplate () {
        const ws = XLSX.utils.aoa_to_sheet([
          ['手机号', '可提现金额', '注意: 金额单位:分,比如一元的话就是填写 100,如果是扣减则填写负值'],
          ['18000000001', 100]
        ])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
        XLSX.writeFile(wb, '批量操作可提现金额模板.xlsx')
      },
      /**
       * 批量操作不可提现余额
       * @param item
       * @param timeline
       * @returns {Promise<unknown>}
       */
      handleBalance (item, timeline) {
        return new Promise(resolve => {
          try {
            if (item['手机号'] === undefined) {
              throw new Error('缺失手机号')
            }
            if (item['可提现金额'] === undefined) {
              throw new Error('缺失可提现金额')
            }

            const uploadData = {
              phone: item['手机号'],
              amount: item['可提现金额'], // 后端单位 分
              balance_type: 'balance' // 不可提现余额
            }
            adjustAgentBalance(uploadData, { silent: true }).then(res => {
              timeline.push({
                color: 'green',
                content: [
                  '代理手机号: ' + item['手机号'] + ' 操作可提现余额: ' + item['可提现金额'] + '(分)'
                ]
              })
            }).catch(e => {
              timeline.push({
                color: 'red',
                content: [
                  '代理手机号: ' + item['手机号'],
                  e.message || ''
                ]
              })
            }).finally(() => {
              resolve()
            })
          } catch (e) {
            timeline.push({
              color: 'red',
              content: [
                '代理手机号: ' + item['手机号'],
                e.message || ''
              ]
            })
            resolve()
          }
        })
      },
      /**
       * 导出批量操作不可提现余额模板
       */
      exportUnextractableBalanceTemplate () {
        const ws = XLSX.utils.aoa_to_sheet([
          ['手机号', '不可提现金额', '注意: 金额单位:分,比如一元的话就是填写 100,如果是扣减则填写负值'],
          ['18000000001', 100]
        ])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
        XLSX.writeFile(wb, '批量操作不可提现金额模板.xlsx')
      },
      /**
       * 批量操作不可提现余额
       * @param item
       * @param timeline
       * @returns {Promise<unknown>}
       */
      handleUnextractableBalance (item, timeline) {
        return new Promise(resolve => {
          try {
            if (item['手机号'] === undefined) {
              throw new Error('缺失手机号')
            }
            if (item['不可提现金额'] === undefined) {
              throw new Error('缺失不可提现金额')
            }

            const uploadData = {
              phone: item['手机号'],
              amount: item['不可提现金额'], // 后端单位 分
              balance_type: 'unextractable_balance' // 不可提现余额
            }
            adjustAgentBalance(uploadData, { silent: true }).then(res => {
              timeline.push({
                color: 'green',
                content: [
                  '代理手机号: ' + item['手机号'] + ' 操作不可提现余额: ' + item['不可提现金额'] + '(分)'
                ]
              })
            }).catch(e => {
              timeline.push({
                color: 'red',
                content: [
                  '代理手机号: ' + item['手机号'],
                  e.message || ''
                ]
              })
            }).finally(() => {
              resolve()
            })
          } catch (e) {
            timeline.push({
              color: 'red',
              content: [
                '代理手机号: ' + item['手机号'],
                e.message || ''
              ]
            })
            resolve()
          }
        })
      }
    }
  }
</script>
